package org.example;

import bean.DB;
import bean.ResponseUtils;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet("/checkOutByStarServlet")
public class checkOutByStarServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        String userId = (String) session.getAttribute("userId");  // 假设存储的是 String 类型的 userId

        if (userId == null) {
            ResponseUtils.sendResponse(response, "用户未登录", "login.jsp");
            return;
        }

        // 尝试将 userId 转换为 Integer
        Integer userIdStar = null;
        try {
            userIdStar = Integer.parseInt(userId);
        } catch (NumberFormatException e) {
            ResponseUtils.sendResponse(response, "无效的用户ID", "login.jsp");
            return;
        }

        // 获取购物车商品的总积分
        double totalStars = 0.0;
        double totalAmount = 0.0; // 用于存储购物车总金额
        DB db = new DB();
        try {
            String getCartItemsSql = "SELECT p.star, ci.quantity, p.price FROM userCart ci " +
                    "JOIN products p ON ci.product_id = p.id " +
                    "WHERE ci.user_id = ?";
            try (Connection conn = db.createConn(); PreparedStatement pstmt = conn.prepareStatement(getCartItemsSql)) {
                pstmt.setInt(1, userIdStar);
                ResultSet cartItemsRs = pstmt.executeQuery();

                while (cartItemsRs.next()) {
                    double star = cartItemsRs.getDouble("star");
                    int quantity = cartItemsRs.getInt("quantity");
                    double price = cartItemsRs.getDouble("price");
                    totalStars += star * quantity; // 计算购物车商品的总积分
                    totalAmount += price * quantity; // 计算购物车商品的总金额
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
            ResponseUtils.sendResponse(response, "查询购物车信息失败", "checkOut.jsp");
            return;
        }

        // 获取当前用户的积分数
        double userStars = 0.0;
        try {
            String getUserStarsSql = "SELECT user_star FROM users WHERE id = ?";
            try (Connection conn = db.createConn(); PreparedStatement pstmt = conn.prepareStatement(getUserStarsSql)) {
                pstmt.setInt(1, userIdStar);
                ResultSet rs = pstmt.executeQuery();
                if (rs.next()) {
                    userStars = rs.getDouble("user_star");
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
            ResponseUtils.sendResponse(response, "获取用户积分失败", "checkOut.jsp");
            return;
        }

        // 判断用户积分是否足够
        if (userStars >= totalStars) {
            // 计算用户可以使用的现金折扣（积分：100 -> 1）
            double discountAmount = (totalStars / 100); // 根据100:1的比例计算折扣金额
            double finalAmount = totalAmount - discountAmount; // 最终应付金额

            // 扣除积分
            try {
                String updateUserStarsSql = "UPDATE users SET user_star = user_star - ? WHERE id = ?";
                try (Connection conn = db.createConn(); PreparedStatement pstmt = conn.prepareStatement(updateUserStarsSql)) {
                    pstmt.setDouble(1, totalStars); // 扣除积分
                    pstmt.setInt(2, userIdStar);
                    pstmt.executeUpdate();
                }

                // 清空购物车
                String deleteCartItemsSql = "DELETE FROM userCart WHERE user_id = ?";
                try (Connection conn = db.createConn(); PreparedStatement pstmt = conn.prepareStatement(deleteCartItemsSql)) {
                    pstmt.setInt(1, userIdStar);
                    pstmt.executeUpdate();
                }

                // 返回结算成功页面并显示优惠金额
                String message = String.format("积分结算成功！您通过积分优惠了 %.2f 元，本次应付金额为 %.2f 元", discountAmount, finalAmount);
                ResponseUtils.sendResponse(response, message, "userinfo.jsp");
            } catch (SQLException e) {
                e.printStackTrace();
                ResponseUtils.sendResponse(response, "结算失败，请稍后重试", "checkOut.jsp");
            }
        } else {
            // 积分不足
            ResponseUtils.sendResponse(response, "您的积分不足，无法进行结算", "checkOut.jsp");
        }
    }
}
